<?php
/**
 * Description: 获取公开课详情及预约情况
 * User: devforma
 * Date: 15/6/6
 * Time: 12:33
 */

class OpenCourseDetail implements iController {
    private $baseUrl = 'http://spark.appublisher.com/plain/static_open_course?class_id=';

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        $user = validateUser($queryArgs);
        if (empty($queryArgs['course_id']) || !is_numeric($queryArgs['course_id']))
            return genOutput(1000);

        if ($user === 1 && !$this->isOpenCourseAvailable($queryArgs['user_id'], $queryArgs['course_id']))
            return genOutput(1000);

        $course = $this->getCourseDetail($queryArgs['course_id']); //获取课程详情

        if (empty($course))
            return genOutput(1000);

        //获取课堂及老师信息
        $sql = 'SELECT t.name, c.start_time, c.end_time FROM `data_teacher` AS t INNER JOIN `data_live_class` AS c ON c.lector_id=t.id
        INNER JOIN `relationship_live_class_and_course` AS r ON c.id=r.class_id AND r.course_id=:course_id';
        $info = $cmsdb->getRow($sql, array(':course_id' => $queryArgs['course_id']));

        //登录用户和非登录用户区别
        $booked = $user === 1 ? $this->isOpenCourseBooked($queryArgs['user_id'], $queryArgs['course_id']) : false;
        return genOutput(1, array(
            'course' => array(
                'cover_pic' => empty($course->cover_pic) ? '' : getSecureUrl($course->cover_pic),
                'name' => $course->course_name,
                'start_time' => empty($info->start_time) ? '' : $info->start_time,
                'end_time' => empty($info->end_time) ? '' : $info->end_time,
                'lector' => empty($info->name) ? '' : $info->name
            ),
            'staticCourseUrl' => $this->getStaticUrl($queryArgs['app_type'], $queryArgs['terminal_type'],
                $queryArgs['user_id']),
            'booked' => $booked,
            'staticCourses' => $this->getStaticCourses()
        ));
    }

    /**
     * 获取往期公开课列表
     */
    private function getStaticCourses() {
        global $cmsdb;
        $ids = getOption('staticCourseUrl');

        if (empty($ids))
            return array();

        $sql = 'SELECT co.id AS course_id, cl.id AS class_id, co.course_name, co.cover_pic, t.name
        FROM `data_live_class` AS cl, `relationship_live_class_and_course` AS r, `data_live_course` AS co, `data_teacher` AS t
        WHERE cl.id=r.class_id AND r.course_id=co.id AND cl.lector_id=t.id AND co.type_id=1 AND cl.id IN ('.$ids.')';
        $records = $cmsdb->getResults($sql);

        $data = array();
        foreach ($records as $r) {
            $data[] = array(
                'course_id' => intval($r->course_id),
                'name' => $r->course_name,
                'cover_pic' => empty($r->cover_pic) ? '' : getSecureUrl($r->cover_pic),
                'lector' => empty($r->name) ? '' : $r->name,
                'course_url' => $this->baseUrl . $r->class_id
            );
        }

        return $data;
    }

    /**
     * 获取往期公开课地址
     * @param string $appType 应用名称
     * @param $terminalType
     * @param $userId
     * @return string
     */
    private function getStaticUrl($appType, $terminalType, $userId) {
        $url = explode(',', getOption('staticCourseUrl'))[0];

        if (!empty($url) && is_numeric($url)) {

            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/plain/static_open_course?class_id='.$url;
            if ($appType === 'quizbank' && $terminalType === 'iOS_phone' && !empty($userId)) {
                $url .= '&user_id='.$userId;
            }

            return $url;
        } elseif (!empty($url) && strpos($url, 'http') !== false) {
            return $url;
        }

        return '';
    }

    /**
     * 获取公开课程信息
     * @param int $courseId 课程id
     * @return mixed
     */
    private function getCourseDetail($courseId) {
        global $cmsdb;

        return $cmsdb->getRow('SELECT `course_name`, `cover_pic` FROM `data_live_course` WHERE `id`=:cid',
            array(':cid' => $courseId));
    }

    /**
     * 是否预定公开课
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @return bool
     */
    private function isOpenCourseBooked($userId, $courseId) {
        global $cmsdb;
        $sql = 'SELECT `is_booked` FROM `gray_user_open_course` WHERE `course_id`=:course_id AND `user_id`=:user_id';
        $booked = $cmsdb->getVar($sql, array(':course_id' => $courseId, ':user_id' => $userId));

        return empty($booked) ? false : true;
    }

    /**
     * 公开课是否可见
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @return bool
     */
    private function isOpenCourseAvailable($userId, $courseId) {
//        global $cmsdb;
//        $sql = 'SELECT `is_available` FROM `gray_user_open_course` WHERE `course_id`=:course_id AND `user_id`=:user_id';
//        $available = $cmsdb->getVar($sql, array(':course_id' => $courseId, ':user_id' => $userId));
//
//        return empty($available) ? false : true;
        return true;
    }
}